<?php

namespace App\Models\Product;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Traits\SerializeDate;

/**
 * 商品模型
 */
class Product extends Model
{
    use SerializeDate;
    use HasFactory;
    // 设置当前模型对应的完整数据表名称
    protected $table = 'product';

    // 定义创建时间的字段
    const CREATED_AT = 'createtime';

    const UPDATED_AT = null;

    const DELETED_AT = 'deletetime';

    protected $appends = [
        'thumbs_text', // 单张图片
        'thumbs_list', // 多张图片
    ];

    protected $casts = [
        'createtime'   => 'datetime:Y-m-d H:i:s',
        'deletetime'   => 'datetime:Y-m-d H:i:s',
    ];


    public function getthumbsTextAttribute($value)
    {
        $ConfigModel = new \App\Models\Config();
        $http = $ConfigModel->where('name', 'url')->value('value');
        $thumbs = '';
        $thumbslist = empty($this->attributes['thumbs']) ?  [] :  explode(',', $this->attributes['thumbs']);
        if (count($thumbslist) > 0) {
            $thumbs =  $http . $thumbslist[0];
        } else {
            $thumbs = $http . '/assets/img/product01.jpg';
        }
        return $thumbs;
    }

    public function getthumbsListAttribute($value)
    {
        $ConfigModel = new \App\Models\Config();
        $url = $ConfigModel->where('name', 'url')->value('value');
        $thumbs = '';
        $thumbslist = empty($this->attributes['thumbs']) ?  '' :  $this->attributes['thumbs'];
        if (!empty($thumbslist)) {
            // 字符串替换
            $str =  str_replace("/uploads/", "$url/uploads/", $thumbslist);
            $thumbs = explode(',', $str);
        } else {
            // 返回默认值
            $thumbs = [$url . '/assets/img/product01.jpg'];
        }
        return $thumbs;
    }
}
